package com.gistone.commis.api.restController;

import com.gistone.commis.constant.Status;
import com.gistone.commis.database.GetBySqlMapper;
import com.gistone.commis.dto.*;
import com.gistone.commis.entity.*;
import com.gistone.commis.mapper.*;
import com.gistone.commis.util.AuditState;
import com.gistone.commis.util.DataTablePageUtil;
import com.gistone.commis.util.DateUtil;
import com.gistone.commis.util.ImageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.OutputStreamWriter;
import java.util.*;

/**
 * Created by wangfan on 2017/5/20.
 */
@RestController("apiOfficeSuppliesController")
@RequestMapping("api/officeSupplies")
public class OfficeSuppliesController {

	private static final Logger logger = LoggerFactory.getLogger(OfficeSuppliesController.class);
	@Autowired
	private GetBySqlMapper getBySqlMapper;
	@Autowired
	CommunityInfoMapper communityInfoMapper;
	@Autowired
	private OfficeSuppliesMapper officeSuppliesMapper;


	@Autowired
	private OfficeSuppliesChangeMapper officeSuppliesChangeMapper;

	@Autowired
	private OfficeSuppliesDetailMapper officeSuppliesDetailMapper;
	@Autowired
	private CommunityMapper communityMapper;

	@Autowired
	private DepartMapper departMapper;
	@Autowired
	private FreeMarkerConfigurer freeMarkerConfigurer;
	@RequestMapping("/download/{id}")
	public void download(@PathVariable Integer id, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/msword");
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		// 下载文件的默认名称
		String filename = "office"+id+".doc";
		response.setHeader("Content-Disposition", "attachment;filename="+filename);
		freeMarkerConfigurer.getConfiguration().setClassForTemplateLoading(getClass(), "/");
		Template template = freeMarkerConfigurer.getConfiguration().getTemplate("officeImg.ftl");
		template.setEncoding("utf-8");
		String webapp = request.getServletContext().getRealPath("/");
		OfficeSupplies item= officeSuppliesMapper.selectByPrimaryKey(id);
		Map<String, Object> root = new HashMap<String, Object>();


		if(null==item.getCommunity().getCommunityName()||item.getCommunity().getCommunityName().isEmpty()) {
			root.put("communityName","");
		}else{
			root.put("communityName",item.getCommunity().getCommunityName());

		}

		if(null==item.getSubmitNumber()) {
			root.put("number","");
		}else{
			root.put("number",item.getSubmitNumber());
		}



		if(null==item.getWorkexpType()||item.getWorkexpType().isEmpty()) {
			root.put("workexpType","");
		}else{
			root.put("workexpType",item.getWorkexpType());
		}


		if(null==item.getPaymentMode()||item.getPaymentMode().isEmpty()) {
			root.put("paymentMode","");
		}else{
			root.put("paymentMode",item.getPaymentMode());
		}


		if(null==item.getComment()||item.getComment().isEmpty()) {
			root.put("comment","");
		}else{
			root.put("comment",item.getComment());
		}
		if(null==item.getSum()) {
			root.put("sum","");
		}else{
			root.put("sum",item.getSum());
		}

		root.put("guanpianDate", "    年  月  日");
		root.put("kezhangDate", "    年  月  日");
		root.put("zuguanDate", "    年  月  日");
		root.put("zhurenDate", "    年  月  日");

		root.put("guanpianSuggest", "");
		root.put("kezhangSuggest", "");
		root.put("zuguanSuggest", "");
		root.put("zhurenSuggest", "");

		root.put("gaizhangImg", ImageUtil.getImageString(ResourceUtils.getFile("classpath:META-INF/resources/blankImg/yinzhangBlank.png").getAbsolutePath()));
		root.put("juweihuiImg", ImageUtil.getImageString(ResourceUtils.getFile("classpath:META-INF/resources/blankImg/juweihuiBlank.png").getAbsolutePath()));
		root.put("guanpianImg", ImageUtil.getImageString(ResourceUtils.getFile("classpath:META-INF/resources/signImg/signBlank.png").getAbsolutePath()));
		root.put("kezhangImg", ImageUtil.getImageString(ResourceUtils.getFile("classpath:META-INF/resources/signImg/signBlank.png").getAbsolutePath()));
		root.put("zuguanImg", ImageUtil.getImageString(ResourceUtils.getFile("classpath:META-INF/resources/signImg/signBlank.png").getAbsolutePath()));
		root.put("zhurenImg", ImageUtil.getImageString(ResourceUtils.getFile("classpath:META-INF/resources/signImg/signBlank.png").getAbsolutePath()));






		root.put("jwhDate", DateUtil.DATEtoString(item.getRegisterTime(),"yyyy年MM月dd日"));

		CommunityInfo ci = new CommunityInfo();
		ci.setCommunityId(item.getCommunityId());
		List<CommunityInfo> list = communityInfoMapper.selectSelective(ci);
		if (list.size() > 0) {
			CommunityInfo communityInfo = list.get(list.size() - 1);
			root.put("gaizhangImg", ImageUtil.getImageString(ResourceUtils.getFile("classpath:META-INF/resources/comImg/" + communityInfo.getReserveB()).getAbsolutePath()));
			root.put("juweihuiImg", ImageUtil.getImageString(ResourceUtils.getFile("classpath:META-INF/resources/signImg/" + communityInfo.getReserveA()).getAbsolutePath()));

		}

		String sql = "select tb_office_supplies_change.*,tb_user.image,tb_user.user_type_id from tb_office_supplies_change,tb_user where   tb_user.user_id =tb_office_supplies_change.current_auditor_id " +
				"AND  tb_office_supplies_change.supplies_id =" + "'" + item.getSuppliesId() + "'";
		List<Map> data = new ArrayList<>();
		List<Map> results = this.getBySqlMapper.findRecords(sql);
		for (Map result : results) {
			Integer userTypeId = (Integer) result.get("user_type_id");
			if (userTypeId == 6) {
				root.put("guanpianDate", DateUtil.DATEtoString((Date)result.get("current_datetime"),"yyyy年MM月dd日"));

				root.put("guanpianImg", ImageUtil.getImageString(ResourceUtils.getFile("classpath:META-INF/resources/signImg/" + result.get("image").toString()).getAbsolutePath()));

				if (null == result.get("suggest") || result.get("suggest").toString().isEmpty()) {
					root.put("guanpianSuggest", "");
				} else {
					root.put("guanpianSuggest", result.get("suggest").toString());

				}

				data.add(result);
			}
			if (userTypeId == 7) {
				root.put("kezhangDate", DateUtil.DATEtoString((Date)result.get("current_datetime"),"yyyy年MM月dd日"));

				root.put("kezhangImg", ImageUtil.getImageString(ResourceUtils.getFile("classpath:META-INF/resources/signImg/" + result.get("image").toString()).getAbsolutePath()));
				if (null == result.get("suggest") || result.get("suggest").toString().isEmpty()) {
					root.put("kezhangSuggest", "");
				} else {
					root.put("kezhangSuggest", result.get("suggest").toString());
				}
			}
			if (userTypeId == 8) {
				root.put("zuguanDate", DateUtil.DATEtoString((Date)result.get("current_datetime"),"yyyy年MM月dd日"));

				root.put("zuguanImg", ImageUtil.getImageString(ResourceUtils.getFile("classpath:META-INF/resources/signImg/" + result.get("image").toString()).getAbsolutePath()));
				if (null == result.get("suggest") || result.get("suggest").toString().isEmpty()) {
					root.put("zuguanSuggest", "");
				} else {
					root.put("zuguanSuggest", result.get("suggest").toString());
				}
			}
			if (userTypeId == 9) {
				root.put("zhurenDate", DateUtil.DATEtoString((Date)result.get("current_datetime"),"yyyy年MM月dd日"));

				root.put("zhurenImg", ImageUtil.getImageString(ResourceUtils.getFile("classpath:META-INF/resources/signImg/" + result.get("image").toString()).getAbsolutePath()));
				if (null == result.get("suggest") || result.get("suggest").toString().isEmpty()) {
					root.put("zhurenSuggest", "");
				} else {
					root.put("zhurenSuggest", result.get("suggest").toString());
				}
			}

		}

		String d =DateUtil.DATEtoString(item.getRegisterTime(),"yyyy-MM-dd");
		root.put("registerTime",d);

		List<OfficeSuppliesDetail>  l =officeSuppliesDetailMapper.selectBySuppliesId(item.getSuppliesId());

		root.put("list", l);




		template.process(root, new OutputStreamWriter(response.getOutputStream(),"utf-8"));
	}



	/**
	 * 根据id获取办公经费信息
	 * @param id
	 * @return
	 */

	@RequestMapping(method = RequestMethod.GET, value = "/{id}")
	public OfficeSupplies officeSupplies(@PathVariable int id) {
		OfficeSupplies officeSupplies =officeSuppliesMapper.selectByPrimaryKey(id);
		return officeSupplies;
	}


	@Transactional
	@RequestMapping(method = RequestMethod.POST, value = "/muticreate")
	public Result muticreate(HttpServletRequest request, HttpServletResponse response,OfficeSupplies officeSupplies ) {
		Date date= new Date();
		HttpSession httpSession = request.getSession();
		User user = (User) httpSession.getAttribute("userInfo");
		officeSupplies.setUserId(user.getUserId());
		officeSupplies.setPersonName(user.getRealName());
		officeSupplies.setRegisterTime(officeSupplies.getRegisterTime());


		try {
			if (null == officeSupplies.getCommunityId()) {
                officeSupplies.setCommunityId(user.getCommunityId());
            }
			officeSupplies.setIsOff(0);
			if (null == officeSupplies.getSubmitNumber()) {
				officeSupplies.setSubmitNumber(1);
			}
			if (null == officeSupplies.getDepartId()) {
                officeSupplies.setDepartId(user.getDepartId());
            }


			if (officeSuppliesMapper.insertSelective(officeSupplies) > 0) {

//                if (officeSupplies.getHasDetail() == 1) {// 如果有详细信息，则保存
                if (true) {// 如果有详细信息，则保存
                    String[] no = request.getParameterValues("no");
                    String[] suppliesName = request.getParameterValues("suppliesName");
                    String[] unitCostStr = request.getParameterValues("unitCost");
                    String[] countStr = request.getParameterValues("count");
                    String[] cost = request.getParameterValues("cost");

                    for (int i = 0; i < suppliesName.length; i++) {

                    	if(!suppliesName[i].isEmpty()) {

							OfficeSuppliesDetail officeSuppliesDetail = new OfficeSuppliesDetail();

							officeSuppliesDetail.setNo(Integer.valueOf(no[i]));
							officeSuppliesDetail.setSuppliesName(suppliesName[i]);
							officeSuppliesDetail.setCount(Integer.valueOf(countStr[i]));
							officeSuppliesDetail.setUnitCost(Double.valueOf(unitCostStr[i]));
							officeSuppliesDetail.setSuppliesId(officeSupplies.getSuppliesId());
							officeSuppliesDetail.setCost(Double.valueOf(cost[i]));

							officeSuppliesDetailMapper.insert(officeSuppliesDetail);
						}

                    }
                }
                OfficeSuppliesChange officeSuppliesChange = new OfficeSuppliesChange();
                officeSuppliesChange.setSuppliesId(officeSupplies.getSuppliesId());
                officeSuppliesChange.setCurrentState(AuditState.WATING);
                officeSuppliesChange.setCurrentAuditorId(user.getUserId());
                officeSuppliesChange.setLastAuditorId(user.getUserId());
                officeSuppliesChange.setCurrentDatetime(date);
                officeSuppliesChange.setLastDatetime(date);
				officeSuppliesChange.setAmount(officeSupplies.getSum());
                officeSuppliesChange.setSubmitNumber(officeSupplies.getSubmitNumber());

                officeSuppliesChange.setIsValid(false);


                if (officeSuppliesChangeMapper.insert(officeSuppliesChange) > 0) {
                    logger.info("保存项目信息成功");
                } else {
                    logger.info("保存项目信息失败");
                    response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);

                }
            } else {
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }
		} catch (NumberFormatException e) {
			logger.info("错误");
			return new Result(Status.ERROR,"error","");
		}


		return new Result("chengg");

	}

	/**
	 * 新建办公经费信息
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@Transactional
	@RequestMapping(method = RequestMethod.POST, value = "/create")
	public EditorResult<OfficeSupplies> create(HttpServletRequest request, HttpServletResponse response) {
		OfficeSupplies officeSupplies = new OfficeSupplies();
		Date date= new Date();
		HttpSession httpSession = request.getSession();
		User user = (User) httpSession.getAttribute("userInfo");
		officeSupplies.setUserId(user.getUserId());
		officeSupplies.setPersonName(user.getRealName());
		officeSupplies.setRegisterTime(date);
		EditorResult<OfficeSupplies> officeSuppliesEditorResult = new EditorResult<>();
		List<FieldError> fieldErrorList = new ArrayList<>();
		getOfficeSupplies (request, "data[0][", officeSupplies,fieldErrorList);
		if(null==officeSupplies.getCommunityId()){
			officeSupplies.setCommunityId(user.getCommunity().getCommunityId());
		}
		officeSupplies.setIsOff(0);
		officeSupplies.setSubmitNumber(1);
		if(null==officeSupplies.getDepartId()){
			officeSupplies.setDepartId(1);
		}



        if(fieldErrorList.size()>0){
			logger.error("字段格式错误");
            officeSuppliesEditorResult.setFieldErrors(fieldErrorList);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return officeSuppliesEditorResult;
        }
		if (officeSuppliesMapper.insertSelective(officeSupplies) > 0) {
			List<OfficeSupplies> data = new ArrayList<>();
			data.add(officeSuppliesMapper.selectByPrimaryKey(officeSupplies.getSuppliesId()))	;
			officeSuppliesEditorResult.setData(data);

			OfficeSuppliesChange officeSuppliesChange = new OfficeSuppliesChange();
			officeSuppliesChange.setSuppliesId(officeSupplies.getSuppliesId());
			officeSuppliesChange.setCurrentState(AuditState.WATING);
			officeSuppliesChange.setCurrentAuditorId(user.getUserId());
			officeSuppliesChange.setLastAuditorId(user.getUserId());
			officeSuppliesChange.setCurrentDatetime(date);
			officeSuppliesChange.setLastDatetime(date);
			officeSuppliesChange.setSubmitNumber(officeSupplies.getSubmitNumber());

			officeSuppliesChange.setIsValid(false);


			if(officeSuppliesChangeMapper.insert(officeSuppliesChange)>0){
				logger.info("保存项目信息成功");
			}else{
				logger.info("保存项目信息失败");
				response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);

			}
		} else {
			response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
		}


		return officeSuppliesEditorResult;

	}

	/**
	 * 批量修改办公经费信息， id以,号分割
	 *
	 * @param houseIdStr
	 * @param request
	 * @return
	 */

	@Transactional
	@RequestMapping(method = RequestMethod.PUT, value = "/edit")
	public Object edit(@RequestParam("id") String houseIdStr, HttpServletRequest request, HttpServletResponse response) {
		HttpSession httpSession = request.getSession();
		User user = (User) httpSession.getAttribute("userInfo");
		String[] arr = houseIdStr.split(",");
		EditorResult<OfficeSupplies> officeSuppliesEditorResult = new EditorResult<>();
		List<OfficeSupplies> data =new ArrayList<>();
		for (int i = 0; i < arr.length; i++) {
			int officeSuppliesId = Integer.valueOf(arr[i]);
			OfficeSupplies officeSupplies = new OfficeSupplies();
			officeSupplies.setSuppliesId(officeSuppliesId);
			List<FieldError> fieldErrorList = new ArrayList<>();
			officeSupplies.setUserId(user.getUserId());
			getOfficeSupplies(request, "data[" + officeSuppliesId + "][", officeSupplies, fieldErrorList );
			if(fieldErrorList.size()>0){
				logger.error("字段错误");
				officeSuppliesEditorResult.setFieldErrors(fieldErrorList);
				response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
				return officeSuppliesEditorResult;
			}
			OfficeSupplies os = officeSuppliesMapper.selectByPrimaryKey(officeSuppliesId);
			int lastSubmitNO=os.getSubmitNumber();
			int currentSubmitNO =officeSupplies.getSubmitNumber();
			if (officeSuppliesMapper.updateByPrimaryKeySelective(officeSupplies) > 0) {
				os= officeSuppliesMapper.selectByPrimaryKey(officeSuppliesId);
				data.add(os);
				OfficeSuppliesChange officeSuppliesChange;
				if(os.getIsDelete()==0) {
					if (lastSubmitNO == currentSubmitNO && user.getUserTypeId() == 1) {//更改信息
						officeSuppliesChange = new OfficeSuppliesChange();
						officeSuppliesChange.setSuppliesId(os.getSuppliesId());
						officeSuppliesChange.setCurrentState(AuditState.Edit);
						officeSuppliesChange.setCurrentAuditorId(user.getUserId());
						officeSuppliesChange.setLastAuditorId(user.getUserId());
//						officeSuppliesChange.setLastDatetime(officeSupplies.);
						officeSuppliesChange.setCurrentDatetime(new Date());
						officeSuppliesChange.setSubmitNumber(officeSupplies.getSubmitNumber());

						officeSuppliesChange.setIsValid(true);
					} else {//重新提交
						officeSuppliesChange = new OfficeSuppliesChange();
						officeSuppliesChange.setSuppliesId(os.getSuppliesId());
						officeSuppliesChange.setCurrentState(AuditState.RESUBMIT);
						officeSuppliesChange.setCurrentAuditorId(user.getUserId());
						officeSuppliesChange.setLastAuditorId(user.getUserId());
//						officeSuppliesChange.setLastDatetime(officeSupplies.);
						officeSuppliesChange.setCurrentDatetime(new Date());
						officeSuppliesChange.setSubmitNumber(officeSupplies.getSubmitNumber());

						officeSuppliesChange.setIsValid(false);
					}
				}else {

					officeSuppliesChange = new OfficeSuppliesChange();
					officeSuppliesChange.setSuppliesId(os.getSuppliesId());
					officeSuppliesChange.setCurrentState(AuditState.DELETE);
					officeSuppliesChange.setCurrentAuditorId(user.getUserId());
					officeSuppliesChange.setLastAuditorId(user.getUserId());
//						officeSuppliesChange.setLastDatetime(officeSupplies.);
					officeSuppliesChange.setCurrentDatetime(new Date());
					officeSuppliesChange.setSubmitNumber(officeSupplies.getSubmitNumber());

					officeSuppliesChange.setIsValid(true);

				}
				


				if(officeSuppliesChangeMapper.insert(officeSuppliesChange)>0){
					logger.info("保存办公经费日志信息成功");
				}else{
					logger.info("保存办公经费日志信息失败");
					response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);

				}

				

			}else{
				response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
			}


		}
		officeSuppliesEditorResult.setData(data);
		return officeSuppliesEditorResult;


	}


	/**
	 * 办公经费删除
	 * 通过办公经费ID批量删除房屋信息， id以,号分割
	 *
	 * @param officeSuppliesIdStr
	 * @param response
	 * @return
	 */
	@Transactional
	@RequestMapping(method = RequestMethod.DELETE, value = "/remove")
	public Object remove(@RequestParam("id") String officeSuppliesIdStr, HttpServletResponse response) {
		String[] arr = officeSuppliesIdStr.split(",");
		EditorResult<OfficeSupplies> officeSuppliesEditorResult = new EditorResult<>();
		for (int i = 0; i < arr.length; i++) {
			int officeSuppliesId = Integer.valueOf(arr[i]);
			OfficeSupplies officeSupplies =new OfficeSupplies();
			officeSupplies.setIsDelete(1);
			officeSupplies.setSuppliesId(officeSuppliesId);
			if (officeSuppliesMapper.updateByPrimaryKeySelective(officeSupplies) > 0) {
				System.out.println("删除" + officeSuppliesId + "成功！");


			} else {
				response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
			}
		}
		return officeSuppliesEditorResult;


	}

	/**
	 * dataTables 表单数据返回
	 *
	 * @param request
	 * @return
	 */

	@Transactional
	@RequestMapping(method = RequestMethod.GET, value = "/pageDatatables")
	public DataTablePageUtil<OfficeSupplies>  pageDatatables(HttpServletRequest request, OfficeSupplies officeSupplies) {
//		HttpSession httpSession = request.getSession();
//		User user = (User) httpSession.getAttribute("userInfo");
//		logger.info("用户信息：" + user.toString());
//		int community_id = user.getCommunity().getCommunityId();
//		officeSupplies.setCommunityId(community_id);

		List<Community> communities =communityMapper.findCommunitys();
		Options os =new Options();
		List<Option> optionList =new ArrayList<>();
		for (Community community : communities) {

			Option option =new Option();
			option.setLabel(community.getCommunityName());
			option.setValue(community.getCommunityId());
			optionList.add(option);


		}
		os.setCommunityId(optionList);
		List<Depart> departs =departMapper.findDeparts();
		optionList =new ArrayList<>();
		for (Depart depart : departs) {

			Option option =new Option();
			option.setLabel(depart.getDepartName());
			option.setValue(depart.getDepartId());
			optionList.add(option);


		}

		os.setDepartId(optionList);



		DataTablePageUtil<OfficeSupplies> dataTable = new DataTablePageUtil<>(request);
		officeSupplies.setIsDelete(0);
		PageHelper.startPage(dataTable.getPage_num(), 10);
		List<OfficeSupplies> list = officeSuppliesMapper.selectSelective(officeSupplies);
		PageInfo<OfficeSupplies> pageInfo =new PageInfo<>(list);
		System.out.println(list.size());
		dataTable.setDraw(dataTable.getDraw());
		dataTable.setData(pageInfo.getList());
		dataTable.setOptions(os);
		dataTable.setRecordsTotal((int)pageInfo.getTotal());
		dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
		//返回数据到页面

		return dataTable;

	}
	
	@Transactional
	@RequestMapping(method = RequestMethod.GET, value = "/officeSuppliesComNotify")
	public DataTablePageUtil<Map>  officeSuppliesComNotify(HttpServletRequest request,Integer isOff) {
		HttpSession httpSession = request.getSession();
		User user = (User) httpSession.getAttribute("userInfo");
		String sql = "select p.*,c.community_name from tb_office_supplies p,tb_community c where   " +
				"p.community_id = c.community_id " +
				" and p.is_delete=0 AND p.community_id =" + "'"+user.getCommunityId()+"'";
		if(null!=isOff){
			sql=sql+"  and  p.is_off =" + "'"+isOff+"'";
		}






		DataTablePageUtil<Map> dataTable = new DataTablePageUtil<>(request);
		PageHelper.startPage(dataTable.getPage_num(), 10);
		List<Map> list =		this.getBySqlMapper.findRecords(sql);
		PageInfo<Map> pageInfo =new PageInfo<>(list);
		System.out.println(list.size());
		dataTable.setDraw(dataTable.getDraw());
//		for (int i = 0; i < pageInfo.getList().size(); i++) {
//			Map map =pageInfo.getList().get(i);
//			String d = DateUtil.DATEtoString((Date)map.get("pp_date"),"yyyy-MM-dd");
//			System.out.println(d);
//			map.put("pp_date",d);
//
//
//		}
		dataTable.setData(pageInfo.getList());
		dataTable.setRecordsTotal((int)pageInfo.getTotal());
		dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
		//返回数据到页面

		return dataTable;

	}

	@Transactional
	@RequestMapping(method = RequestMethod.GET, value = "/officeSuppliesNotify")
	public DataTablePageUtil<Map>  officeSuppliesNotify(HttpServletRequest request) {
		HttpSession httpSession = request.getSession();
		User user = (User) httpSession.getAttribute("userInfo");
		int userId =user.getUserId();
		String sql = "select p.*,c.community_name,u.real_name,pc.* from tb_office_supplies_change pc,tb_user u,tb_office_supplies p,tb_community c where   " +
				"u.user_id =pc.current_auditor_id and pc.supplies_id=p.supplies_id and u.community_id = c.community_id " +
				" and pc.is_valid =0 and p.is_delete=0 AND u.parent_id =" + "'"+userId+"'";







		DataTablePageUtil<Map> dataTable = new DataTablePageUtil<>(request);
		PageHelper.startPage(dataTable.getPage_num(), 10);
		List<Map> list =		this.getBySqlMapper.findRecords(sql);
		PageInfo<Map> pageInfo =new PageInfo<>(list);
		System.out.println(list.size());
		dataTable.setDraw(dataTable.getDraw());
//		for (int i = 0; i < pageInfo.getList().size(); i++) {
//			Map map =pageInfo.getList().get(i);
//			String d = DateUtil.DATEtoString((Date)map.get("pp_date"),"yyyy-MM-dd");
//			System.out.println(d);
//			map.put("pp_date",d);
//
//
//		}
		dataTable.setData(pageInfo.getList());
		dataTable.setRecordsTotal((int)pageInfo.getTotal());
		dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
		//返回数据到页面

		return dataTable;

	}


	@Transactional
	@RequestMapping(method = RequestMethod.GET, value = "/changeDatatables")
	public DataTablePageUtil<Map>  changeDatatables(HttpServletRequest request,Integer id) {
		HttpSession httpSession = request.getSession();
		User user = (User) httpSession.getAttribute("userInfo");

		String sql = "select * from tb_office_supplies_change,tb_user where tb_office_supplies_change.current_auditor_id =tb_user.user_id and  supplies_id=" + "'"+id+"'";

		DataTablePageUtil<Map> dataTable = new DataTablePageUtil<>(request);
		PageHelper.startPage(dataTable.getPage_num(), 10);
		List<Map> list =		this.getBySqlMapper.findRecords(sql);
		PageInfo<Map> pageInfo =new PageInfo<>(list);
		System.out.println(list.size());
		dataTable.setDraw(dataTable.getDraw());
		dataTable.setData(pageInfo.getList());
		dataTable.setRecordsTotal((int)pageInfo.getTotal());
		dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
		//返回数据到页面

		return dataTable;

	}




	@Transactional
	@RequestMapping(method = RequestMethod.PUT, value = "/officeSuppliesEdit")
	public Object officeSuppliesNotifyEdit (@RequestParam("id") String idStr, HttpServletRequest request, HttpServletResponse response) {
		HttpSession httpSession = request.getSession();
		User user = (User) httpSession.getAttribute("userInfo");

		String[] arr = idStr.split(",");
		EditorResult<Map> officeSuppliesEditorResult = new EditorResult<>();
		List<Map> data =new ArrayList<>();
		OfficeSupplies officeSupplies =null;

		for (int i = 0; i < arr.length; i++) {
			int officeSuppliesChangeId = Integer.valueOf(arr[i]);
			OfficeSuppliesChange officeSuppliesChange =officeSuppliesChangeMapper.selectByPrimaryKey(officeSuppliesChangeId);

			if (null == officeSuppliesChange) {

				response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
				return null;
			}
			officeSupplies =officeSuppliesMapper.selectByPrimaryKey(officeSuppliesChange.getSuppliesId());
			if (officeSupplies == null) {
				response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
				return null;
			}
			List<FieldError> fieldErrorList = new ArrayList<>();
			String prefix="data[" + officeSuppliesChangeId + "][";
			try {
				int currentState= Integer.valueOf(request.getParameter(prefix + "currentState]"));
				officeSuppliesChange.setIsValid(true); //true代表这条记录的上级领导已经操作
				if(officeSuppliesChangeMapper.updateByPrimaryKey(officeSuppliesChange)>0){
					logger.info("更新项目信息成功");
				}else{
					logger.info("更新项目日志信息失败");
					response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);

				}

				OfficeSuppliesChange fc = new OfficeSuppliesChange();//产生新的修改日志
				fc.setSuppliesId(officeSupplies.getSuppliesId());
				fc.setCurrentState(currentState);
				fc.setCurrentAuditorId(user.getUserId());
				fc.setLastAuditorId(officeSuppliesChange.getCurrentAuditorId());
				fc.setLastDatetime(officeSuppliesChange.getCurrentDatetime());
				fc.setCurrentDatetime(new Date());
				fc.setSubmitNumber(officeSuppliesChange.getSubmitNumber());
				fc.setIsValid(true);//直接返回，不再向上级申报
				String sql = "select current_auditor_id  from tb_office_supplies_change where supplies_id = " +officeSupplies.getSuppliesId()+" and current_auditor_id !=" +user.getUserId()+"";
				List<Map> back_userIdMaps = this.getBySqlMapper.findRecords(sql);

				double amount =officeSuppliesChangeMapper.getNewlyAmountById(officeSupplies.getSuppliesId());
				if(currentState==3){//建议
					String suggest =request.getParameter(prefix + "suggest]");
					fc.setSuggest(suggest);
					if(null!=request.getParameter(prefix + "amount]")&&!request.getParameter(prefix + "amount]").isEmpty()){
						amount =Double.valueOf(request.getParameter(prefix + "amount]"));
					}
					/*else{
						fc.setAmount(officeSupplies.getSum());
					}*/
					/*officeSupplies.setIsOff(3);//建议
					for (Map back_userIdMap : back_userIdMaps) {
						sql = "insert into tb_back_notify (type_name,project_id,project_name,person_id,flag) values ('officeSupplies',"+officeSupplies.getSuppliesId()+",'"+officeSupplies.getWorkexpType()+"',"+back_userIdMap.get("current_auditor_id")+",3)";

						this.getBySqlMapper.insert(sql);

					}*/

					if(officeSupplies.getSum()<500&&officeSupplies.getUser().getParentId()==user.getUserId()&&user.getUserTypeId()==6){
						officeSupplies.setIsOff(7); //同意完成申报，社区未查看通知
						officeSupplies.setSum(amount);

					}else {
						if (user.getRealName().equals("王洪星") && officeSupplies.getSum() < 1000) {//判断经费金额若低于1000元且审批人是王洪星 计划审批结束
							officeSupplies.setIsOff(7); //同意完成申报，社区未查看通知
							officeSupplies.setSum(amount);
						} else {
							if (user.getUserId() == user.getParentId()) {//同意，不存在上级领导
								officeSupplies.setIsOff(7); //同意完成申报，社区未查看通知
								officeSupplies.setSum(amount);
							} else {//同意，且存在上级领导

								fc.setIsValid(false);//需要等待上级领导处理

							}
						}
					}




				}else if(currentState==1){//同意 判定用户是否还有领导
					if(officeSupplies.getSum()<500&&officeSupplies.getUser().getParentId()==user.getUserId()&&user.getUserTypeId()==6){
						officeSupplies.setIsOff(7); //同意完成申报，社区未查看通知
						officeSupplies.setSum(amount);
					}else {
						if (user.getRealName().equals("王洪星") && officeSupplies.getSum() < 1000) {//判断经费金额若低于1000元且审批人是王洪星 计划审批结束
							officeSupplies.setIsOff(7); //同意完成申报，社区未查看通知
							officeSupplies.setSum(amount);
						} else {
							if (user.getUserId() == user.getParentId()) {//同意，不存在上级领导
								officeSupplies.setIsOff(7); //同意完成申报，社区未查看通知
								officeSupplies.setSum(amount);
							} else {//同意，且存在上级领导

								fc.setIsValid(false);//需要等待上级领导处理

							}
						}
					}



				}else if(currentState==2){//拒绝

					officeSupplies.setIsOff(2);
					for (Map back_userIdMap : back_userIdMaps) {
						sql = "insert into tb_back_notify (type_name,project_id,project_name,person_id,flag) values ('officeSupplies',"+officeSupplies.getSuppliesId()+",'"+officeSupplies.getWorkexpType()+"',"+back_userIdMap.get("current_auditor_id")+",2)";

						this.getBySqlMapper.insert(sql);

					}
				}
				fc.setAmount(amount);
				if (officeSuppliesMapper.updateByPrimaryKeySelective(officeSupplies) > 0){
					logger.info("更新项目信息成功");
				}else{
					logger.info("更新项目信息失败");
					response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);

				}
				if(officeSuppliesChangeMapper.insertSelective(fc)>0){
					logger.info("保存项目信息成功");
				}else{
					logger.info("保存项目信息失败");
					response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);

				}



			} catch (NumberFormatException e) {
				logger.error("格式不正确，必须为整形");
				FieldError fieldError =new FieldError("amount","格式不正确，必须为整型");
				fieldErrorList.add(fieldError);
			}
			if(fieldErrorList.size()>0){
				logger.error("字段错误");
				officeSuppliesEditorResult.setFieldErrors(fieldErrorList);
				response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
				return officeSuppliesEditorResult;
			}

			String sql = "select p.*,c.community_name,u.real_name,pc.* from tb_office_supplies_change pc,tb_user u,tb_office_supplies p,tb_community c where   " +
					"u.user_id =pc.current_auditor_id and pc.supplies_id=p.supplies_id and u.community_id = c.community_id " +
					"and pc.is_valid =0 AND  u.parent_id =" + "'"+user.getUserId()+"' and pc.change_id =" +"'"+officeSuppliesChangeId+"'";

			List<Map> list =		this.getBySqlMapper.findRecords(sql);
			if(list.size()>0){
				data.add(list.get(0));
			}




		}
		officeSuppliesEditorResult.setData(data);
		return officeSuppliesEditorResult;


	}


	@Transactional
	@RequestMapping(method = RequestMethod.PUT, value = "/officeSuppliesComEdit")
	public Object officeSuppliesComNotifyEdit (@RequestParam("id") String idStr, HttpServletRequest request, HttpServletResponse response) {
		HttpSession httpSession = request.getSession();
		User user = (User) httpSession.getAttribute("userInfo");

		String[] arr = idStr.split(",");
		EditorResult<Map> officeSuppliesEditorResult = new EditorResult<>();
		List<Map> data =new ArrayList<>();
		OfficeSupplies officeSupplies =null;

		for (int i = 0; i < arr.length; i++) {
			int officeSuppliesId = Integer.valueOf(arr[i]);

			officeSupplies =officeSuppliesMapper.selectByPrimaryKey(officeSuppliesId);

			List<FieldError> fieldErrorList = new ArrayList<>();
			String prefix="data[" + officeSuppliesId + "][";


			if(null!=request.getParameter(prefix + "is_off]")){
				System.out.println("----------off");
				officeSupplies.setIsOff(1);
				if (officeSuppliesMapper.updateByPrimaryKeySelective(officeSupplies) > 0) {
					logger.info("更新信息成功");
				} else {
					logger.info("更新信息失败");
					response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);

				}
			}



			if(fieldErrorList.size()>0){
				logger.error("字段错误");
				officeSuppliesEditorResult.setFieldErrors(fieldErrorList);
				response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
				return officeSuppliesEditorResult;
			}

			String sql = "select p.*,c.community_name from tb_office_supplies p,tb_community c where   " +
					"p.community_id = c.community_id " +
					" and p.is_delete=0  AND p.community_id =" + "'"+user.getCommunityId()+"'"+
					" and p.supplies_id =" + "'"+officeSuppliesId+"'";

			List<Map> list =		this.getBySqlMapper.findRecords(sql);
			if(list.size()>0){
				data.add(list.get(0));
			}




		}
		officeSuppliesEditorResult.setData(data);
		return officeSuppliesEditorResult;


	}


	private void getOfficeSupplies(HttpServletRequest request, String prefix, OfficeSupplies officeSupplies,List<FieldError> fieldErrorList ) {
		if (null!=request.getParameter(prefix + "communityId]")&&!request.getParameter(prefix + "communityId]").isEmpty()) {
			officeSupplies.setCommunityId(Integer.valueOf(request.getParameter(prefix + "communityId]")));


		}
		if (null!=request.getParameter(prefix + "departId]")&&!request.getParameter(prefix + "departId]").isEmpty()) {
			officeSupplies.setDepartId(Integer.valueOf(request.getParameter(prefix + "departId]")));


		}
		officeSupplies.setSuppliesName(request.getParameter(prefix + "suppliesName]"));

		if (null != request.getParameter(prefix + "unitCost]")&&!request.getParameter(prefix + "unitCost]").isEmpty()) {
			try {
				officeSupplies.setUnitCost(Double.valueOf(request.getParameter(prefix + "unitCost]")));
			} catch (NumberFormatException e) {
				logger.error("格式不正确，必须为整形数字");
				FieldError fieldError = new FieldError("unitCost", "格式不正确，必须为整形数字");
				fieldErrorList.add(fieldError);
			}
		}
		if (null != request.getParameter(prefix + "count]")&&!request.getParameter(prefix + "count]").isEmpty()) {
			try {
				officeSupplies.setCount(Integer.valueOf(request.getParameter(prefix + "count]")));
			} catch (NumberFormatException e) {
				logger.error("格式不正确，必须为整形数字");
				FieldError fieldError = new FieldError("count", "格式不正确，必须为整形数字");
				fieldErrorList.add(fieldError);
			}
		}
		try {
			officeSupplies.setSum(Double.valueOf(request.getParameter(prefix + "sum]")));
		} catch (NumberFormatException e) {
			logger.error("格式不正确，必须为整形数字");
			FieldError fieldError =new FieldError("sum","格式不正确，必须为整形数字");
			fieldErrorList.add(fieldError);
		}
			officeSupplies.setWorkexpType(request.getParameter(prefix + "workexpType]"));

		officeSupplies.setPaymentMode(request.getParameter(prefix + "paymentMode]"));
		officeSupplies.setComment(request.getParameter(prefix + "comment]"));
		if (null != request.getParameter(prefix + "isOff]")&&!request.getParameter(prefix + "isOff]").isEmpty()) {
			try {
				officeSupplies.setIsOff(Integer.valueOf(request.getParameter(prefix + "isOff]")));
			} catch (NumberFormatException e) {
				logger.error("数量格式不正确，必须为整形数字");
				FieldError fieldError = new FieldError("isOff", "格式不正确，必须为整形数字");
				fieldErrorList.add(fieldError);
			}

		}
		if (null != request.getParameter(prefix + "isDelete]")&&!request.getParameter(prefix + "isDelete]").isEmpty()) {
			try {
				int isDelete = Integer.valueOf(request.getParameter(prefix + "isDelete]"));
				officeSupplies.setIsDelete(isDelete);
			} catch (NumberFormatException e) {
				logger.error("数量格式不正确，必须为整形数字");
				FieldError fieldError = new FieldError("isDelete", "格式不正确，必须为整形数字");
				fieldErrorList.add(fieldError);
			}

		}
		if (null != request.getParameter(prefix + "submitNumber]")&&!request.getParameter(prefix + "isDelete]").isEmpty()) {
			try {
				officeSupplies.setSubmitNumber(Integer.valueOf(request.getParameter(prefix + "submitNumber]")));
			} catch (NumberFormatException e) {
				logger.error("数量格式不正确，必须为整形数字");
				FieldError fieldError = new FieldError("submitNumber", "格式不正确，必须为整形数字");
				fieldErrorList.add(fieldError);
			}

		}



	}







}
